﻿@using KC.Web.Account.Constants
@using KC.Framework.Tenant
@using Microsoft.AspNetCore.Authorization
@inject IAuthorizationService AuthorizationService

@{
    ViewBag.Title = "用户管理";
    Layout = "~/Views/Shared/_ListLayout.cshtml";
    @*用户管理-用户角色管理*@
    var canRoleInUser = false;
    @if ((await AuthorizationService.AuthorizeAsync(User, "用户管理-用户角色管理")).Succeeded)
    {
        canRoleInUser = true;
    }
    @*用户管理-冻结/激活用户*@
    var canDongJie = false;
    @if ((await AuthorizationService.AuthorizeAsync(User, "B15DDB6E-6922-4E59-AC07-D8773BB42D0A")).Succeeded)
    {
        canDongJie = true;
    }
    @*用户管理-用户详情*@
    var canUserDetail = false;
    @if ((await AuthorizationService.AuthorizeAsync(User, "1012EBF9-5A21-45CF-870E-CC03AE860B67")).Succeeded)
    {
        canUserDetail = true;
    }
    @*用户管理-删除用户*@
    var canDeleteUser = false;
    @if ((await AuthorizationService.AuthorizeAsync(User, "E617F833-311B-4B4F-A04A-EC17214D6A1B")).Succeeded)
    {
        canDeleteUser = true;
    }
    var dowonloadUrl = Url.Action(ActionName.User.DownLoadExcelTemplate, ControllerName.User);
}

@section styles
    {
    <link href="@(KC.Framework.Base.GlobalConfig.ResWebDomain)js/webuploader/webuploader.css" rel="stylesheet" />
    <link href="~/css/upload.css" rel="stylesheet" />
    <style>
        .webuploader-pick {
            position: relative;
            display: inline-block;
            cursor: pointer;
            padding: 0px 0px;
            color: #2779AA;
            text-align: center;
            vertical-align: middle;
            border-radius: 3px;
            overflow: hidden;
            background: transparent;
        }
    </style>
}
<div id="toolbar">
    <div>
        @*用户管理-保存用户*@
        @if ((await AuthorizationService.AuthorizeAsync(User, "55BD23BA-D892-41A0-A2D3-5E773D832E79")).Succeeded)
        {
            <a href="javascript:void(0)" class="easyui-linkbutton" iconcls="fa fa-plus" onclick="addDatabasePool()">新增</a>
        }
        @*用户管理-保存用户*@
        @if ((await AuthorizationService.AuthorizeAsync(User, "55BD23BA-D892-41A0-A2D3-5E773D832E79")).Succeeded)
        {
            <a href="javascript:void(0)" class="easyui-linkbutton" iconcls="fa fa-pencil" onclick="editDatabasePool()">编辑</a>
        }
        @*用户管理-下载用户Excel模板*@
        @if ((await AuthorizationService.AuthorizeAsync(User, "15E50D59-D883-4D31-9382-F7517F0A16B9")).Succeeded)
        {
            <a href="@dowonloadUrl" class="easyui-linkbutton" iconcls="fa fa-download">下载导入模板</a>
        }
        @*用户管理-导入用户数据*@
        @if ((await AuthorizationService.AuthorizeAsync(User, "41CD0D9C-52C8-48CB-86A2-CFB6A9B1F096")).Succeeded)
        {
            <a id="uploadExcel" href="javascript:void(0)" class="easyui-linkbutton" iconcls="fa fa-upload">导入Excel数据</a>
        }
    </div>

    <div>
        @Html.DropDownList("PositionLevel", (IEnumerable<SelectListItem>)ViewBag.PositionLevels, "请选择部门岗位", new Dictionary<string, object>
        {
            { "class","easyui-combobox" },
            { "id", "PositionLevel" },
            { "data-options","editable: false, required:true" },
            { "panelHeight","auto" },
            { "style", "width:120px" }
        })
        <select id="stat" class="easyui-combobox" name="dept" style="width:100px;" data-options="editable: false,panelHeight:80">
            <option value="999">请选择状态</option>
            <option value="1">冻结</option>
            <option value="0">激活</option>
        </select>

        <input id="searchboxUserName" class="easyui-textbox" data-options="prompt:'请输入用户名'" style="width:100px">
        <input id="searchboxEmail" class="easyui-textbox" data-options="prompt:'请输入邮箱'" style="width:100px">
        <input id="searchboxPhone" class="easyui-textbox" data-options="prompt:'请输入手机号'" style="width:100px">
        <input id="searchboxName" class="easyui-textbox" data-options="prompt:'请输入姓名'" style="width:100px">
        <a href="javascript:void(0)" onclick="reloadDatagrid()" class="easyui-linkbutton" data-options="iconCls:'fa fa-search'">查询</a>
        <a href="javascript:void(0)" onclick="RefreshSearch()" class="easyui-linkbutton" data-options="iconCls:'fa fa-refresh'">刷新</a>

    </div>

</div>
<table id="datagrid"></table>
@section scripts
    {
    <script type="text/javascript" src="@(KC.Framework.Base.GlobalConfig.ResWebDomain)js/webuploader/md5.js"></script>
    <script type="text/javascript" src="@(KC.Framework.Base.GlobalConfig.ResWebDomain)js/webuploader/webuploader.min.js"></script>
    <script type="text/javascript" src="@(KC.Framework.Base.GlobalConfig.ResWebDomain)js/common/com.uploader.js"></script>
    <script type="text/javascript">
        $.extend($.fn.validatebox.defaults.rules, {
            repeatdisplayName: {
                validator: function (value) {
                    var reg = /\d$/;

                    return !reg.test(value);
                },
                message: '请输入有效的姓名'
            }
        });
        $.extend($.fn.validatebox.defaults.rules, {
            repeatUserCode:{
                validator: function (value) {
                    var reg = /^[0-9a-zA-Z]+$/;

                    return reg.test(value);
                },
                message: '请输入有效的用户编号'
            }
        });
        var canDeleteUser = '@canDeleteUser' === 'True';
        var canDongJie = '@canDongJie' === 'True';
        var canRoleInUser = '@canRoleInUser' === 'True';
        var canUserDetail = '@canUserDetail' === 'True';
        $(function() {
            InitDataGrid();

            InitUploader();

            $(".btnImport").hide();
        });

        //按回车查询
        function KeyDown() {
            if (event.keyCode == 13) {
                reloadDatagrid();
            }
        }
        function RefreshSearch() {
            $("#searchboxEmail").searchbox('setValue', '');
            $("#searchboxPhone").searchbox('setValue', '');
            $("#searchboxName").searchbox('setValue', '');
            $('#stat').combobox("setValue", '999');
            $("#PositionLevel").combobox('setValue', '');
            reloadDatagrid();
        }
        function reloadDatagrid() {
            var stat = $('#stat').combobox("getValue");
            if ($('#stat').combobox("getValue") == "999") {
                stat = "";
            }

            $("#datagrid").datagrid("load", {
                email: $("#searchboxEmail").searchbox("getValue"),
                phone: $("#searchboxPhone").searchbox("getValue"),
                name: $("#searchboxName").searchbox("getValue"),
                statType: stat,
                positionLevel: $('#PositionLevel').combobox("getValue")
            });
        }

        var uploader = null;
        var uploadExcelUrl = '@Url.Action(ActionName.User.UploadExcelTemplate, ControllerName.User)';
        function InitUploader() {
            uploader = $.fn.cfwinUploader.upload({
                baseUrl: '/js/webuploader/',
                postUrl: uploadExcelUrl,
                btnAddFile: $('#uploadExcel'),
                //btnContinueAddFile: $('#continueAddFile'),
                //fileList: $('.uploadPicList'),
                type: 1,
                fileNumLimit: 10,
                params: { tenatName: '', blobId: '' },
                configure: {
                    fileMaxSize: 15,
                    fileExt: 'xlsx'
                },
                callback: {
                    uploadProgress: function(file, percentage) {
                        $("#" + file.id + " .progress-bar").css('width', (percentage * 100).toFixed(2) + "%");
                    },
                    uploadComplete: function(file) { //不管成功或者失败，文件上传完成时触发
                    },
                    uploadSuccess: function(file, data) {
                        if (data) {
                            if (data.success) {
                                $.messager.showInfoCenter('系统提示', '上传文件成功！', 1000);
                            } else {
                                $.messager.showErrorCenter('错误消息', data.message);
                            }
                        } else {
                            $.messager.showErrorCenter('错误消息', '上传文件失败！');
                        }

                        $('#datagrid').datagrid('reload');
                        $('#' + file.id).remove();
                    },
                    uploadError: function(file, reason) {
                        $.messager.showErrorCenter('错误消息', '上传文件失败，失败原因：' + reason);
                    },
                    onFileQueued: function(file) {
                        //$('#uploadExcel').hide();
                        uploader.upload();
                    }
                }
            });
        }

        var loadDataUrl = '@Url.Action(ActionName.User.LoadUserList, ControllerName.User)';
        function InitDataGrid() {
            var $dataGrid = $('#datagrid').datagrid({
                //view: detailview,
                url: loadDataUrl,
                method: 'POST',
                idField: 'UserId',
                striped: true,
                fitColumns: true,
                rownumbers: true,
                singleSelect: true,
                pagination: true,
                nowrap: false,
                fit: true,
                pageSize: 10,
                pageList: [10, 20, 50, 100],
                showFooter: false,
                toolbar: "#toolbar",
                columns: [[
                    { field: 'MemberId', title: '用户编号', width: 80, align: 'left' },
                    { field: 'UserName', title: '用户名', width: 80, align: 'left',
                        formatter: function (value, row, index) {
                            var userId = row.UserId;
                            var userName = row.UserName;
                            var tdContext = userName;
                            if (canUserDetail)
                                tdContext = "<a style='cursor:pointer' onclick=openUserPage('" + userId + "','userdetail')>" + userName + "</a>";
                            return tdContext;
                        }
                    },
                    { field: 'DisplayName', title: '姓名', width: 80, align: 'left' },
                    { field: 'Email', title: '邮箱', width: 120, align: 'left' },
                    { field: 'PhoneNumber', title: '手机号', width: 80, align: 'left' },
                    { field: 'OrganizationNames', title: '所属部门', width: 80, align: 'left',
                        formatter: function (value, row, index) {
                            if (value != undefined && value != "") {
                                return value.substr(0, value.length - 1);
                            }
                            return value;
                        }
                    },
                    { field: 'PositionLevelName', title: '部门岗位', width: 60, align: 'left' },
                    { field: 'Stat', title: '状态', width: 60,
                        formatter: function (value, row, index) {
                            if (value == "1") {
                                return "<span style='color:rgb(255, 0, 0);'>已冻结</span>";
                            }
                            return "<span style='color:rgb(0, 0, 255);'>已激活</span>";
                        }
                    },
                    { field: 'c', title: '激活/冻结', width: 60,
                        formatter: function(value, row, index) {
                            if (canDongJie) {
                                if (row.Stat == 1) {
                                    return "<a class='btnContacts' style='cursor: pointer' onclick=operateUser('" + row.UserId + "','" + row.Stat + "')>激活</a>";
                                } else {
                                    return "<a class='btnContacts' style='cursor: pointer'  onclick=operateUser('" + row.UserId + "','" + row.Stat + "')>冻结</a>";
                                }
                            }
                        }
                    },
                    { field: 'ssss', title: '操作', width: 160, align: 'left',
                        formatter: function (value, row, index) {
                            var userId = row.UserId;
                            var userName = row.UserName;

                            var tdContext = '';
                            if (canRoleInUser) {
                                tdContext += '<a class="btnContacts" style="cursor:pointer" onclick="openUserPage(\'' + userId + '\', \'roleinuser\')" >分配角色</a>';
                            }
                            if (canDeleteUser)
                            {
                                tdContext += '<a class="btnDelete" style="cursor:pointer" onclick="removeUser(\'' + userId + '\', \'roleinuser\')" >删除用户</a>';
                            }
                            return tdContext;
                        }
                    }
                ]],
                onBeforeLoad: function(param) {
                    /*var bId = $("#txtBId").val();
                    var AllSearchKey = $("#txtAllSearchKey").val();
                    param.bId = bId;
                    param.AllSearchKey = AllSearchKey;*/
                },
                onLoadSuccess: function(data) {
                    $(".btnContacts").linkbutton({ iconCls: 'fa fa-user' });
                    $(".btnDelete").linkbutton({ iconCls: 'fa fa-trash' });
                    
                    $dataGrid.datagrid("fixRowHeight");
                    //checkGuidelines(pageName, function(result) {
                    //    if (!result)
                    //        initIntro();
                    //});
                },
                onLoadError: function() {
                }
            });
        }
        function searchData(value, name) {
            $('#datagrid').datagrid('unselectAll');
            $('#datagrid').datagrid('load', { "searchKey": name, "searchValue": value });
        }
        function addDatabasePool() {
            var title = "新增用户";
            opentForm('', title);
        }
        function editDatabasePool() {
            var row = $('#datagrid').datagrid('getSelected');
            if (row) {
                var title = "编辑用户";
                opentForm(row.UserId, title);
            } else {
                $.messager.showErrorCenter('系统提示', "请选择需要编辑的数据", 1000);
            }
        }

        var roleInUser = '@Url.Action(ActionName.User.RoleInUser, ControllerName.User)';
        var userDetailUrl = '@Url.Action(ActionName.User.UserDetail, ControllerName.User)';
        function openUserPage(userId, type) {
            var url = "";
            var queryString = "id=" + userId;
            if (type == "roleinuser") {
                url = roleInUser;
            } else if (type == "userdetail") {
                url = userDetailUrl;
            }
            MainPage_PostMessage("openSubPage", url, queryString);
        }

        var getFormUrl = '@Url.Action(ActionName.User.GetUserForm, ControllerName.User)';
        var saveFormUrl = '@Url.Action(ActionName.User.SaveUser, ControllerName.User)';
        var AuditPendingUrl = '@Url.Action("AuditPendingUSer", "User")';
        function opentForm(id, title) {
            var dialog = $.easyui.showDialog({
                title: title,
                width: 500,
                height: 400,
                href: getFormUrl + "?id=" + id,
                modal: true,
                topMost: false,
                enableHeaderContextMenu: false,
                enableApplyButton: false,
                onSave: function(d) {
                    var organizationName = $('#OrganizationId').combotree('getValues');
                    var validate = d.form("enableValidation").form("validate");
                    var postData = d.form("getData");
                    postData['organizations'] = organizationName;

                    if (validate) {
                        $.easyui.loading({ msg: '正在保存数据，请稍等...' });
                        $.ajax({
                            async: true,
                            type: "post",
                            dataType: "json",
                            url: saveFormUrl,
                            data: postData,
                            success: function(data) {
                                if (data.success) {
                                    d.window('close');
                                    if (data.Result) {
                                        $.messager.showInfoCenter('系统提示', '保存数据成功。', 1000);
                                        $('#datagrid').datagrid('reload');
                                    } else {
                                        $.messager.showErrorCenter('错误消息', data.message);
                                    }
                                } else {
                                    $.messager.showInfoCenter('系统提示', data.message);
                                }
                            },
                            complete: function() {
                                $.easyui.loaded();
                            }
                        });
                        return false;
                    } else {
                        return false;
                    }
                },
                onLoad: function() {
                    var f = $(this), ret = $.fn.dialog.defaults.onLoad();
                    f.form("disableValidation").form("enableValidation");
                    return ret;
                }
            });
        }

        var adminUserId = '@RoleConstants.AdminUserId';
        var currentUserId = '@ViewBag.meUserId';
        var freezeOrActivationUrl = '@Url.Action(ActionName.User.FreezeOrActivation, ControllerName.User)';
        function operateUser(id, stat) {
            var adminUserId = adminUserId;
            var meUserId = currentUserId;
            if (id.contains(meUserId)) {
                $.messager.showInfoCenter('系统提示', "无法更改用户自身的状态！", 1000);
                return;
            }
            if (id.contains(adminUserId)) {
                $.messager.showInfoCenter('系统提示', "无法更改系统管理员的状态！", 1000);
                return;
            }
            var title = "";
            if (stat == 0) {
                title = "冻结之后将去除该用户所有角色且不可恢复,是否确认改变状态";
            } else {
                title = "是否确定激活该用户?";
            }
            $.messager.confirm("系统提示", title,
                function(r) {
                    if (r) {
                        $.ajax({
                            url: freezeOrActivationUrl,
                            async: true,
                            type: 'post',
                            dataType: 'json',
                            data: { id: id },
                            success: function(data) {
                                if (data.success) {
                                    if (data.Result) {
                                        $('#datagrid').datagrid('reload');
                                        $.messager.showInfoCenter('系统提示', '操作成功！', 1000);
                                    } else {
                                        $.messager.showErrorCenter('错误消息', '操作失败！');
                                    }
                                } else {
                                    $('#datagrid').datagrid('reload');
                                    $.messager.showInfoCenter('系统提示', data.message);
                                }
                            },
                            error: function(e) {
                                //var error = JSON.parse(e.responseText).Message;
                                $.easyui.loaded();
                                $.messager.showInfoCenter('系统提示', '抱歉,你不具有当前操作的权限');
                            }
                        });
                    }
                });
        }

        var removeUrl = '@Url.Action(ActionName.User.RemoveUser, ControllerName.User)';
        function removeUser(userId) {
            var row = $('#datagrid').datagrid('getSelected');
            if (row) {
                $.messager.confirm('系统提示', '删除之后将去除该用户所有角色(所有系统)且不可恢复,是否确定删除选中数据?', function(r) {
                    if (r) {
                        $.easyui.loading({ msg: '正在保存数据，请稍等...' });
                        $.post(removeUrl, { id: userId }, function(data) {
                            if (data.success) {
                                if (data.Result) {
                                    $('#datagrid').datagrid('reload');
                                    $.messager.showInfoCenter('系统提示', '删除数据成功。', 1000);
                                } else {
                                    $.messager.showErrorCenter('错误消息', '删除数据失败。');
                                }
                            } else {
                                $.messager.showInfoCenter('系统提示', data.message);
                            }
                            $.easyui.loaded();
                        }, 'json');
                    }
                });
            }
        }

        var existUserEmailUrl = '@Url.Action(ActionName.User.ExistUserEmail, ControllerName.User)';
        function existUserEmail(id) {
            $.post(existUserEmailUrl, { id: id, email: $("#Email").val() }, function(data) {
                if (data == "result") {
                    $.messager.showInfoCenter('系统提示', '邮箱【' + $("#Email").val() + '】已存在,请重新输入。');
                    $("#Email").val("");
                }
                if (data == "result1") {
                    $.messager.showInfoCenter('系统提示', '邮箱【' + $("#Email").val() + '】正在审批中，请重新输入');
                    $("#Email").val("");

                }
            }, 'json');
        }
        var existUserPhoneUrl = '@Url.Action(ActionName.User.ExistUserPhone, ControllerName.User)';
        function existUserPhone(id) {
            $.post(existUserPhoneUrl, { id: id, phone: $("#PhoneNumber").val() }, function(data) {
                if (data == "result") {
                    $.messager.showInfoCenter('系统提示', '手机号【' + $("#PhoneNumber").val() + '】已存在,请重新输入。');
                    $("#PhoneNumber").val("");
                }
                if (data == "result1") {
                    $.messager.showInfoCenter('系统提示', '手机号【' + $("#PhoneNumber").val() + '】正在审批中，请重新输入');
                    $("#PhoneNumber").val("");
                }
            }, 'json');
        }
        var existUserNameUrl = '@Url.Action(ActionName.User.ExistUserName, ControllerName.User)';
        function existUserName(id) {
            $.post(existUserNameUrl, { id: id, userName: $("#UserName").val() }, function(data) {
                    if (data == "result") {
                        $.messager.showInfoCenter('系统提示', '用户名【' + $("#UserName").val() + '】已存在,请重新输入。');
                        $("#UserName").val("");
                    }
                    if (data == "result1") {
                        $.messager.showInfoCenter('系统提示', '用户名【' + $("#UserName").val() + '】正在审批中,请重新输入。');
                        $("#UserName").val("");
                    }
                },
                'json');
        }
    </script>
}
